package com.zrb.mobile.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zrb.applib.utils.AppSetting;
import com.zrb.discover.UserCardDetailActivity;
import com.zrb.discover.widget.DrawableCenterTextView;
import com.zrb.discover.widget.TimelineView;
import com.zrb.mobile.Discover_MainFragment;
import com.zrb.mobile.MoneyDetailActivity;
import com.zrb.mobile.News_ShareActivity;
import com.zrb.mobile.ProjectDetailActivity;
import com.zrb.mobile.PushLiuYanActivity;
import com.zrb.mobile.R;

import com.zrb.mobile.adapter.model.DynamicDto;
import com.zrb.mobile.adapter.model.DynamicDto.ExtraInfo;
 
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.CircleImageView;
import com.zrb.mobile.utility.AlertDialog;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.TimeUtil;

public class Discover_listAdapter extends BaseAdapter {
	private static final String LOG_TAG = "Discover_listAdapter";
   
	
	
	final class ViewHolder {
 		
		public LinearLayout content_bg;
		public CircleImageView iv_avatar;
		public TextView publish_person;
		
		public TextView industry;
		public TextView company;
		public TextView position;
		
	 	public TextView edit;
		
 		public TextView discover_title;
 		public TextView discover_content;
 		 
		public TextView textView4;
		public TextView textView7;
		public TextView textView6;
 
	 
 
 		public ImageView certification;
 		public RelativeLayout businessCard;
 		
 		public LinearLayout discover_actionbar;
  
	}

	final class TimelineViewHolder {
		public TimelineView timeline;
		public TextView time;
	}

	public interface onActionlistener {
		void onAttentionEvent(int postion);

		void showLoginDialog(String msg);
	}

	onActionlistener monActionlistener;
	DisplayImageOptions options;
	private Context mcontext;
	private Drawable isFocus, NoFocus, defautAvatar;
	public List<DynamicDto> mCurrentDatas = new ArrayList<DynamicDto>();
	private LayoutInflater mInflater;
	private long mTempTime = 0;

	int FundColor=Color.parseColor("#b68f85");
	int ProjectColor=Color.parseColor("#8ea0be");
	
	public void setOnAction(onActionlistener IonActionlistener) {

		monActionlistener = IonActionlistener;
	}

	public Discover_listAdapter(Context context) {
		mcontext = context;
		this.mInflater = LayoutInflater.from(context);
		NoFocus = context.getResources().getDrawable(R.drawable.found_like_off);
		isFocus = context.getResources().getDrawable(R.drawable.found_like_on);
		defautAvatar = context.getResources().getDrawable(R.drawable.portrait);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.portrait)
				.showImageForEmptyUri(R.drawable.portrait)
				.showImageOnFail(R.drawable.portrait).cacheInMemory(true)
				.cacheOnDisc(true).build();
	}

	// public void setAll(List<tmpTextDto> items) {
	// CurrentDatas.clear();
	// CurrentDatas.addAll(items);
	// }

	public int getCount() {
		if (mCurrentDatas != null) {
			return mCurrentDatas.size();
		}
		return 0;
	}

	public DynamicDto getCurItem(int position) {
		if (mCurrentDatas.size() == 0) {
			return null;
		}
		return mCurrentDatas.get(position);
	}

	public void addAll(List<DynamicDto> tmpDtos,boolean isAppend) {
		if(!isAppend){
			mTempTime = 0;
			mCurrentDatas.clear();
		}
  		addTimeLine(tmpDtos);
	}

	private void addTimeLine(List<DynamicDto> tmpDtos) {
		for (int index = 0; index < tmpDtos.size(); index++) {
			DynamicDto tempDiscoverDto = tmpDtos.get(index);
			
		/*	DynamicDto tmp=new DynamicDto();*/
			long time = tempDiscoverDto.createTime;

			if (!TimeUtil.isSameDayOfMillis(time, mTempTime)) {
				DynamicDto discoverDto = new DynamicDto();
				discoverDto.showType = DynamicDto.TYPE_TIMELINE;
				discoverDto.createTime = time;
				mTempTime = time;
				mCurrentDatas.add(discoverDto);
			} else {
				tempDiscoverDto.showType = DynamicDto.TYPE_DESCRIPTION;
			}
			mCurrentDatas.add(tempDiscoverDto);
		}
	}

 

	public long getMinIdTime() {
		if (mCurrentDatas != null && mCurrentDatas.size() > 0)
			return   mCurrentDatas.get(mCurrentDatas.size() - 1).createTime;
		return -1;
	}

	@Override
	public DynamicDto getItem(int position) {
		return mCurrentDatas.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public int getItemViewType(int position) {
		int type = DynamicDto.TYPE_DESCRIPTION;
		if (mCurrentDatas.get(position).isTimeline()) {
			type = DynamicDto.TYPE_TIMELINE;
		}
		return type;
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		TimelineViewHolder timelineViewholder = null;
		int type = getItemViewType(position);
		if (convertView == null) {
			switch (type) {
			case DynamicDto.TYPE_DESCRIPTION:
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.discover_list_item, parent, false);
				initDescriptionItem(convertView, holder);
				initClickListener(holder);
				break;
			case DynamicDto.TYPE_TIMELINE:
				timelineViewholder = new TimelineViewHolder();
				convertView = mInflater.inflate(R.layout.timeline_item, parent, false);
				initTimelineItem(convertView, timelineViewholder);
				break;
			default:
				break;
			}
		} else {
			switch (type) {
			case DynamicDto.TYPE_DESCRIPTION:
				holder = (ViewHolder) convertView.getTag();
				break;
			case DynamicDto.TYPE_TIMELINE:
				timelineViewholder = (TimelineViewHolder) convertView.getTag();
				break;
			default:
				break;
			}
		}

		switch (type) {
		case DynamicDto.TYPE_DESCRIPTION:
			 setDescriptionResource(holder, position);
			//Log.d("testhei","getView hei:" + convertView.getHeight());
			break;
		case DynamicDto.TYPE_TIMELINE:
			setTimelineResource(timelineViewholder, position);
			break;
		default:
			break;
		}
		return convertView;
	}
	
	 protected void animScale(final View likeView) {
	        ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 1.5f, 1.0f, 1.5f,
	                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
	        scaleAnimation.setDuration(200);
	        scaleAnimation.setFillAfter(true);
	        scaleAnimation.start();
	        likeView.startAnimation(scaleAnimation);
	        likeView.postDelayed(new Runnable() {

	            @Override
	            public void run() {
	                ScaleAnimation scaleAnimation = new ScaleAnimation(1.5f, 1.0f, 1.5f, 1.0f,
	                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
	                scaleAnimation.setDuration(200);
	                scaleAnimation.setFillAfter(true);
	                likeView.startAnimation(scaleAnimation);
	            }

	        }, 200);
	    }

	private void initClickListener(ViewHolder holder) {
	 	 holder.edit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(null==v.getTag()) return;
				int pos = Integer.parseInt(v.getTag().toString());
				DynamicDto dto = mCurrentDatas.get(pos);
 				if(dto.type==Constants.Choice_Project)
				  ProjectDetailActivity.launch(mcontext, Long.parseLong(dto.target), dto.title);
				else
				  MoneyDetailActivity.launch(mcontext, Long.parseLong(dto.target), dto.title);
			}
		}); 
	 	holder.iv_avatar.setOnClickListener(new OnClickListener() {
 			@Override
			public void onClick(View v) {
 				if(null==v.getTag()) return;
 				if(AppSetting.curUser==null){
 					showLoginDialog("您还没有登陆，登陆后才能查看相关功能!");
 					return;
 				}
				int pos = Integer.parseInt(v.getTag().toString());
				DynamicDto dto = mCurrentDatas.get(pos);
				// long userId, String name, String avatar, String org, String job, String industry
			 
				UserCardDetailActivity.launch(mcontext, dto.userId, dto.extraInfo.realname, dto.extraInfo.avatar, dto.extraInfo.org,
						                               dto.extraInfo.positionName, dto.extraInfo.industryName);
 
			}
		}); 
	 
	}

	private void initDescriptionItem(View convertView, ViewHolder holder) {
 
		holder.content_bg= (LinearLayout) convertView.findViewById(R.id.discover_contentbar);
		holder.iv_avatar = (CircleImageView) convertView.findViewById(R.id.iv_avatar);
		holder.businessCard = (RelativeLayout) convertView.findViewById(R.id.business_card);
 		
		holder.publish_person = (TextView) convertView.findViewById(R.id.publish_person);
		holder.industry = (TextView) convertView.findViewById(R.id.industry_tag);
		holder.company = (TextView) convertView.findViewById(R.id.company_tag);
		holder.position = (TextView) convertView.findViewById(R.id.postion_tag);
	 
		holder.discover_title = (TextView) convertView.findViewById(R.id.tv_discover_title_tv);
		holder.discover_content = (TextView) convertView.findViewById(R.id.tv_discover_content);
   
		holder.edit = (TextView) convertView.findViewById(R.id.tv_discover_edit);
 		holder.discover_actionbar=(LinearLayout)convertView.findViewById(R.id.discover_actionbar);
		 
 		holder.certification = (ImageView) convertView.findViewById(R.id.img_certification);
		
		convertView.setTag(holder);
	}

	private void initTimelineItem(View convertView, TimelineViewHolder holder) {
		holder.time = (TextView) convertView.findViewById(R.id.timelineIcon);
		holder.timeline = (TimelineView) convertView.findViewById(R.id.timelines);
		convertView.setTag(holder);
	}

	private void setDescriptionResource(ViewHolder holder, int position) {
		ExtraInfo textDto = mCurrentDatas.get(position).extraInfo;
		// 加载图片
		if (!TextUtils.isEmpty(textDto.avatar)) {
			ImageLoader.getInstance().displayImage( AppSetting.mediaServer + textDto.avatar, holder.iv_avatar, options);
		} else {
			holder.iv_avatar.setImageDrawable(defautAvatar);
		}

		holder.publish_person.setText(TextUtils.isEmpty(textDto.realname) ? "匿名": textDto.realname);
 	 	holder.industry.setText(textDto.industryName);
	 	holder.company.setText(textDto.org);
	 	holder.position.setText(textDto.positionName);
	 	

	/*	positionStr = mcontext.getResources().getString(R.string.secrecy);*/
	
	 
		
		int curType=mCurrentDatas.get(position).type;
		holder.content_bg.setBackgroundResource(curType == Constants.DiscoverProjectIntent
				                                               ? R.drawable.cashbubble
						                                       : R.drawable.cashbubble2);
 
 		
		holder.discover_content.setText(mCurrentDatas.get(position).title);
		
		switch(curType){
		case Constants.Publish_Fund:
			 holder.discover_title.setText("我有"+Constants.FLAG+"投资需求");
			 holder.discover_title.setTextColor(FundColor);
			break;
		case Constants.Publish_Project:
			 holder.discover_title.setText("我有"+Constants.FLAG+"资金需求");
			 holder.discover_title.setTextColor(ProjectColor);
			break;
		case Constants.Choice_Fund:
			 holder.discover_title.setText("入选"+Constants.FLAG+"资金精选");
			 holder.discover_title.setTextColor(FundColor);
			break;
		case Constants.Choice_Project:
			 holder.discover_title.setText("入选"+Constants.FLAG+"项目精选");
			 holder.discover_title.setTextColor(ProjectColor);
			break;
		
		}
  	 
		
		boolean isChoice=curType==Constants.Choice_Project||curType==Constants.Choice_Fund;
		 holder.discover_actionbar.setVisibility(isChoice ?View.VISIBLE:View.GONE);
		 holder.edit.setTag(position);
		if(isChoice){
			 holder.edit.setText(curType==Constants.Choice_Project? "项目详情":"资金详情");
 		}
  		 
  		holder.iv_avatar.setTag(position);
	}

	private void setTimelineResource(TimelineViewHolder holder, int position) {
		
		holder.timeline.setDotsVisibility(true);
		if (position == 0) {
			holder.timeline.setTopLineVisibility(false);
		} else {
			holder.timeline.setTopLineVisibility(true);
		}
		DynamicDto textDto = mCurrentDatas.get(position);
		long time = textDto.createTime;
		holder.time.setText(TimeUtil.formatTime(time));
	}

	@Override
	public boolean isEnabled(int position) {
/*		if ((mCurrentDatas.get(position).auth == Constants.PROJECT_SCENE_AUTH)
				|| mCurrentDatas.get(position).auth == Constants.PROJECT_MATERIALS_AUTH) {
			return true;
		}*/
		return false;
	}

	public static final String USER_ORG = "org";
	public static final String USER_INDUSTRY = "industry";
	public static final String USER_JOB = "job";
	public static final String USER_AVATAR_URL = "avatar";
 

	private EditItemInterface mEditInterface = null;
	private EditItemInterface mBusinessInterface = null;
	
	public interface EditItemInterface{
		public void click(DynamicDto discoverDto);
	}
	
	public void setEditItemInterface(EditItemInterface editItemInterface){
		mEditInterface = editItemInterface;
	}
	
	public void setBusinessItemInterface(EditItemInterface editItemInterface){
		mBusinessInterface = editItemInterface;
	}
	
	public void modifyData(DynamicDto dto){
		for(int index = 0;index < mCurrentDatas.size();index++){
			if(mCurrentDatas.get(index).id == dto.id){
				mCurrentDatas.remove(index);
				mCurrentDatas.add(index, dto);
				break;
			}
		}
	}
	
	public void delData(long id){
		for(int index = 0;index < mCurrentDatas.size();index++){
			if(mCurrentDatas.get(index).id == id){
				mCurrentDatas.remove(index);
				break;
			}
		}
	}
	
	 void showLoginDialog(String msg) {
  		
		 new AlertDialog(mcontext).builder().setTitle("登录提示")
		   .setMsg(msg)
		   .setPositiveButton("马上登录", new OnClickListener() {
			@Override
			public void onClick(View v) {
 				User_phone_login.launch((Activity)mcontext, false);
 			}
		    }).setNegativeButton("取消").show();
	}
}